﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using Model;
using Repository;
using UI.Areas.Admin.Models;
using UI.Helper;

namespace UI.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        #region action

        public ActionResult Index()
        {
            var repository = RepositoryManager.CreateProductRepository();

            var lst = Paging(1, repository) ?? new List<Product>();

            return View(lst);
        }

        public ActionResult PagingData(int pageIndex)
        {
            var repository = RepositoryManager.CreateProductRepository();

            var lst = Paging(pageIndex, repository) ?? new List<Product>();

            return View("Index", lst);
        }

        public ActionResult Delete(int id)
        {
            var repository = RepositoryManager.CreateProductRepository();

            var objDelete = repository.HaveImage(id);

            if (objDelete == null)
            {
                TempData[Constants.MESSAGE] = "Không tìm thấy sản phẩm cần xóa.";
            }

            else
            {
                if (objDelete.Images != null && objDelete.Images.Count > 0)
                    TempData[Constants.MESSAGE] = "Đang có hình ảnh thuộc sản phẩm '" + objDelete.Name + "' nên không thể xóa.";
                else
                {
                    repository.Delete(objDelete);

                    TempData[Constants.MESSAGE] = "Đã xóa thành công";
                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult DeleteAll(string id)
        {
            string[] arrId = id.Split(',');

            var i = 0;

            List<Product> lst = new List<Product>();

            var repository = RepositoryManager.CreateProductRepository();

            foreach (var s in arrId)
            {
                var objDelete = repository.HaveImage(Convert.ToInt32(s));

                if (objDelete == null)
                {
                    TempData[Constants.MESSAGE] = "Không tìm thấy sản phẩm cần xóa.";

                    break;
                }
                else
                {
                    if (objDelete.Images != null && objDelete.Images.Count > 0)
                    {
                        TempData[Constants.MESSAGE] = "Đang có hình ảnh thuộc sản phẩm '" + objDelete.Name +
                                                            "' nên không thể xóa.";

                        break;
                    }
                    else
                        lst.Add(objDelete);
                }

                i++;
            }

            if (i == arrId.Length)
            {
                foreach (var category in lst)
                    repository.Delete(category);

                TempData[Constants.MESSAGE] = "Đã xóa thành công";
            }

            return RedirectToAction("Index");
        }

        public ActionResult Add()
        {
            var repository = RepositoryManager.CreateCategoryRepository();

            var provinceRep = RepositoryManager.CreateProvinceRepository();

            var districteRep = RepositoryManager.CreateDistrictRepository();

            var model = new ProductModel { Categories = repository.GetAll(), Provinces = provinceRep.GetAll() };

            if (model.Provinces.Count > 0)
                model.Districts = districteRep.GetAllByProvince(model.Provinces[0].Id);

            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Add(ProductModel productModel)
        {
            var catRepository = RepositoryManager.CreateCategoryRepository();

            var provinceRep = RepositoryManager.CreateProvinceRepository();

            var districteRep = RepositoryManager.CreateDistrictRepository();

            var proRepository = RepositoryManager.CreateProductRepository();

            if (productModel != null)
            {
                var objCategory = catRepository.GetById(productModel.CategoryId);

                var objProvince = provinceRep.GetById(productModel.ProvinceId);

                var objDistrict = districteRep.GetById(productModel.DistrictId);

                if (objCategory != null && objProvince != null && objDistrict != null)
                {
                    var objProduct = new Product()
                    {
                        Category = objCategory,
                        Name = productModel.Name,
                        Address = productModel.Address,
                        Description = productModel.Description,
                        IsHot = productModel.IsHot,
                        Priority = productModel.Priority,
                        Province = objProvince,
                        District = objDistrict
                    };

                    proRepository.Insert(objProduct);

                    TempData[Constants.MESSAGE] = "Đã thêm thành công";
                }

                return RedirectToAction("Index", "Product");
            }

            return View();
        }

        public ActionResult Edit(int id)
        {
            var catRepository = RepositoryManager.CreateCategoryRepository();

            var proRepository = RepositoryManager.CreateProductRepository();

            var provinceRep = RepositoryManager.CreateProvinceRepository();

            var districteRep = RepositoryManager.CreateDistrictRepository();

            var objEdit = proRepository.GetById(id);

            if (objEdit != null)
            {
                var model = new ProductModel()
                                {
                                    Categories = catRepository.GetAll(),
                                    Provinces = provinceRep.GetAll(),
                                    Districts = districteRep.GetAll(),
                                    Description = objEdit.Description,
                                    CategoryId = objEdit.Category == null ? 0 : objEdit.Category.Id,
                                    ProvinceId = objEdit.Province == null ? 0 : objEdit.Province.Id,
                                    DistrictId = objEdit.District == null ? 0 : objEdit.District.Id,
                                    IsHot = objEdit.IsHot,
                                    Name = objEdit.Name,
                                    Address = objEdit.Address,
                                    Priority = objEdit.Priority,
                                    ProductId = objEdit.Id
                                };

                return View(model);
            }

            return View("Index");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(ProductModel productModel)
        {
            var catRepository = RepositoryManager.CreateCategoryRepository();

            var provinceRep = RepositoryManager.CreateProvinceRepository();

            var districteRep = RepositoryManager.CreateDistrictRepository();

            var proRepository = RepositoryManager.CreateProductRepository();

            if (productModel != null)
            {
                var objProduct = proRepository.GetById(productModel.ProductId);

                if (objProduct != null)
                {
                    objProduct.Category = catRepository.GetById(productModel.CategoryId);
                    objProduct.Province = provinceRep.GetById(productModel.ProvinceId);
                    objProduct.District = districteRep.GetById(productModel.DistrictId);
                    objProduct.Name = productModel.Name;
                    objProduct.Address = productModel.Address;
                    objProduct.Description = productModel.Description;
                    objProduct.IsHot = productModel.IsHot;
                    objProduct.Priority = productModel.Priority;

                    proRepository.Update(objProduct);

                    TempData[Constants.MESSAGE] = "Đã cập nhật thành công";
                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult Search(string id)
        {
            var repository = RepositoryManager.CreateProductRepository();

            var lst = repository.SearchByName(id);

            return View(lst);
        }

        public JsonResult GetDistrictByProvince(int id)
        {
            var districteRep = RepositoryManager.CreateDistrictRepository();

            var res = districteRep.GetAllByProvince(id);

            List<ListItem> list = new List<ListItem>();

            foreach (var dis in res)
            {
                ListItem item = new ListItem() { Text = dis.Name, Value = dis.Id.ToString() };
                list.Add(item);
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetDistrictByProvinceLeft(int id)
        {
            var districteRep = RepositoryManager.CreateDistrictRepository();

            var res = districteRep.GetAllByProvince(id);

            List<ListItem> list = new List<ListItem>();

            foreach (var dis in res)
            {
                ListItem item = new ListItem() { Text = dis.Name, Value = dis.Id.ToString() };
                list.Add(item);
            }

            ListItem oitem = new ListItem() { Text = "Tất cả", Value = "0" };
            list.Add(oitem);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        #endregion action

        #region private method

        private List<Product> Paging(int pageIndex, ProductRepository repository)
        {
            var totalPage = repository.GetTotalPage(Constants.NUM_OF_ROWS);

            ViewData[Constants.TOTAL_PAGE] = totalPage;

            ViewData[Constants.PAGE_INDEX] = pageIndex;

            if (pageIndex > totalPage)
                return null;

            var lst = repository.Paging(pageIndex, Constants.NUM_OF_ROWS);

            return lst;
        }

        #endregion private method
    }
}